#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "Log.hpp"
#include "InetAddr.hpp"

enum
{
    SOCK_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

using func_t = std::function<std::string(const std::string &)>;

const int defaultsock = -1;
const int gbacklog = 16;

class TcpServer;

class ThreadData
{
public:
    ThreadData(int fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t func)
        : _port(port), _func(func), _listensock(defaultsock), _isrunning(false)
    {
    }

    void InitServer()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LOG(FATAL, "socket create error\n");
            exit(SOCK_ERROR);
        }
        LOG(DEBUG,"socket create success, fd: %d\n",_listensock);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(struct sockaddr_in));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error, fd:%d\n", _listensock);
            exit(BIND_ERROR);
        }

        LOG(DEBUG,"bind success, fd : %d \n",_listensock);

        // 绑定成功，开始监听
        n = listen(_listensock, gbacklog);
        if (n < 0)
        {
            LOG(FATAL, "listen error, fd: %d\n", _listensock);
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG,"listen success , fd: %d\n",_listensock);
    }

    void Service(int sockfd, InetAddr addr)
    {
        LOG(DEBUG,"get a new link,info: %s:%d ,fd: %d\n",addr.Ip().c_str(),addr.Port(),sockfd);

        std::string clientaddr = "[" + addr.Ip() + ":" + std::to_string(addr.Port()) + "]# ";

        while (true)
        {
            // 接收消息
            char inbuffer[1024];
            ssize_t s = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (s > 0)
            {
                inbuffer[s] = 0;

                std::cout << clientaddr << inbuffer << std::endl;

                //接收命令执行结果
                std::string result = _func(inbuffer);//重点！！

                send(sockfd,result.c_str(),result.size(),0);//发送结果
            }
            else if (s == 0)
            {
                LOG(INFO, "%s quit ... \n", clientaddr.c_str());
                break;
            }
            // 读取失败
            else
            {
                LOG(ERROR, "read error\n");
                break;
            }

            close(sockfd);
        }
    }

    //重点！！
    static void *Handler(void *args)
    {
        pthread_detach(pthread_self()); // 与主线程分离

        ThreadData *td = static_cast<ThreadData *>(args); // 强转

        // 调用
        td->self->Service(td->sockfd, td->clientaddr);

        delete td; // 释放

        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(struct sockaddr_in);

            int sockfd = accept(_listensock, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error, listenfd: %d\n", _listensock);
                continue;
            }

            // 连接成功，开始任务

            // 多线程
            pthread_t pid;
            ThreadData *data = new ThreadData(sockfd, InetAddr(peer), this);
            pthread_create(&pid, nullptr, Handler, data);
        }
        _isrunning = false;
    }
    ~TcpServer()
    {
        if (_listensock > defaultsock)
            close(_listensock);
    }

private:
    int _listensock; // 用于监听
    uint16_t _port;  // 端口
    func_t _func;    // 任务
    bool _isrunning; // 是否在运行
};
